package com.sann.config;


import com.mchange.v2.c3p0.ComboPooledDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;

import javax.sql.DataSource;

//@Resource(name = "classpath:/mysql.properties")//
//@PropertySource("classpath:mysql.properties")
//@Configuration
@Slf4j
public class JdbcConfiguration {

    @Value("${jdbc.driver}")
    private String driver ;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    /**
     * 创建一个 QueryRunner Bean对象，并存入IOC容器
     * @param dataSource
     * @return
     */
    @Bean(name="runner")
    @Scope(value="prototype")
    public QueryRunner createQueryRunner(@Qualifier("dataSource") DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    /**
     * 创建一个数据源对象，并存入IOC容器
     * @return
     */
    @Bean(name="dataSource")
    public DataSource createDataSource(){
        log.info("driver: {}, url:{}, username:{}, password:{}", driver,url,username,password);
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
